package com.wasu.sdk_ott.service

import android.app.Service
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import com.wasu.constant.TAG
import com.wasu.sdk_ott.provider.RESERVATION_DB_CHID
import com.wasu.sdk_ott.provider.RESERVATION_DB_STARTDATE

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 查询直播预约节目单服务
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2023/9/4
 */
class LiveReservationEpService: Service() {

    override fun onCreate() {
        super.onCreate()
        Log.v(TAG, "--LiveReservationEpService--onCreate--")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val extra = intent?.getStringExtra("Schedual_ep")?: ""
        val chId = intent?.getStringExtra(RESERVATION_DB_CHID)?: ""
        Log.v(TAG, "--LiveReservationEpService--onStartCommand--extra--$extra; chId:$chId")
        val startDate = intent?.getLongExtra(RESERVATION_DB_STARTDATE, 0L)?: 0L

        if (chId.isNotEmpty() || extra.isNotEmpty()){
            // 发送广播到UI层，首次启动服务，是在UILApplication中
            LiveReservationHelper.sendEpReservationReceiver(this@LiveReservationEpService, chId, extra)
            // 重新查询下一个即将到时间的预约节目单，并再次定时启动本服务，用于广播发送到UI
            LiveReservationHelper.queryEpReservation(this@LiveReservationEpService, delete = {
                // 删除已经到时间的预约节目单
                LiveReservationHelper.deleteEpReservation(this@LiveReservationEpService, "chid=? and startdate=?", arrayOf(chId, startDate.toString()))
            }, isFirst = false)
        }else {
            // 重新查询下一个即将到时间的预约节目单，并再次定时启动本服务，用于广播发送到UI
            LiveReservationHelper.queryEpReservation(this@LiveReservationEpService, isFirst = true)
        }

        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent?): IBinder? {
        Log.v(TAG, "--LiveReservationEpService--onBind--")
        return null
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.v(TAG, "--LiveReservationEpService--onUnbind--")
        return super.onUnbind(intent)
    }

    override fun unbindService(conn: ServiceConnection) {
        super.unbindService(conn)
        Log.v(TAG, "--LiveReservationEpService--unbindService--")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.v(TAG, "--LiveReservationEpService--onDestroy--")
    }

}